package com.jtjrenren.android.taxi.passenger.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.library.utils.DatabaseManager;


/**
 * Created by Administrator on 2016/1/7.
 */
public class DbBaseDao {
    private DatabaseManager manger;

    protected String tableName;
    protected Context context;
    private SQLiteDatabase db;

    public DbBaseDao(Context context,String tableName){
        this.tableName=tableName;
        this.context=context;

        initDbManger(context);
    }

    /**
     * 初始化数据库管理类
     * @param context
     */
    private void initDbManger(Context context) {
        if (!manger.isInit()) {
            DbHelper helper = new DbHelper(context);
            manger.initializeInstance(helper);
        }
        manger = DatabaseManager.getInstance();
    }
    protected long insert(String nullColumnHack, ContentValues values) {
        long insert = -1;
        db = manger.openDatabase();
        if (db.isOpen()) {
            insert = db.insert(tableName, nullColumnHack, values);
        }
        closeDb();
        return insert;
    }

    protected int update(ContentValues values, String whereClause,
                         String[] whereArgs) {
        int update = -1;
        db = manger.openDatabase();
        if (db.isOpen()) {
            update = db.update(tableName, values, whereClause, whereArgs);
        }
        closeDb();
        return update;
    }

    protected int del(String whereClause, String[] whereArgs) {
        int delete = -1;
        db = manger.openDatabase();
        if (db.isOpen()) {
            delete = db.delete(tableName, whereClause, whereArgs);
        }
        closeDb();
        return delete;
    }

    protected Cursor query(String[] columns, String selection,
                           String[] selectionArgs, String order) {
        db = manger.openDatabase();
        return db.query(tableName, columns, selection, selectionArgs, null,
                null, order);
    }

    public void closeDb() {
        manger.closeDatabase();
    }

}
